package com.simoniu.generatekey;

import com.simoniu.entity.Students;
import com.simoniu.entity.Users;
import com.simoniu.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

public class UseGenerateKeyDemo {

    //新增一个学生资料，获得新增学生资料的主键
    public void useGenerateKey(Students s) {
        String sql = "insert into students (sname,gender) values (?,?)";
        try (Connection conn = DBUtil.getConnection()
             ; PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            pstmt.setString(1, s.getSname());
            pstmt.setString(2, s.getGender());
            pstmt.executeUpdate();
            //获得主键
            ResultSet rs = pstmt.getGeneratedKeys();
            long key = -1;
            //注意：这里必须把游标指向第一条记录。
            if (rs.next()) {
                key = rs.getLong(1);
            }
            s.setSid((int) key);

            System.out.println("新增的用户资料是：");
            System.out.println(s);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private String generateUUIDKey() {
        //生成日期前缀
        String prefix = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE).replaceAll("-", "");


        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //UUID转换为hashCode
        String temp = Math.abs(uuid.hashCode()) + "";
        //不够十位前面补零
        if (temp.length() < 10) {
            String str = temp;
            for (int j = 0; j < 10 - temp.length(); j++) {
                str = "0" + str;
            }
            temp = str;
        }
        //打印卡号
        //System.out.println(prefix+temp);
        return prefix + temp;

    }

    //获得UUID生成的主键
    public void useGenerateUUIDKeys(Users user) {
        String sql = "insert into users (uid,username,password) values (?,?,?)";
        try (Connection conn = DBUtil.getConnection()
             ; PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, generateUUIDKey());
            pstmt.setString(2, user.getUsername());
            pstmt.setString(3, user.getPassword());

            pstmt.executeUpdate();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Students s = new Students(100, "宋小宝", "男");
        UseGenerateKeyDemo demo = new UseGenerateKeyDemo();
        //demo.useGenerateKey(s);
        //新增是个用户资料
        for(int i=11;i<20;i++){
            Users u = new Users("100","guest"+i,"123456");
            demo.useGenerateUUIDKeys(u);
        }

    }
}
